package com.zhiche.lisa.lspm.service.driver.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.lspm.dao.mapper.driver.DriverLicenseAttachMapper;
import com.zhiche.lisa.lspm.dao.model.driver.DriverLicenseAttach;
import com.zhiche.lisa.lspm.dao.model.driver.DriverLicenseAttachHistory;
import com.zhiche.lisa.lspm.dao.model.lsp.LspLicenseAttach;
import com.zhiche.lisa.lspm.service.driver.IDriverLicenseAttachHistoryService;
import com.zhiche.lisa.lspm.service.driver.IDriverLicenseAttachService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 司机证照附件 service impl
 *
 * @author lbl
 * @since 2018-05-28
 */
@Service
public class DriverLicenseAttachServiceImpl extends ServiceImpl<DriverLicenseAttachMapper, DriverLicenseAttach> implements IDriverLicenseAttachService {
    @Autowired
    private IDriverLicenseAttachHistoryService driverLicenseAttachHistoryService;

    @Override
    public void delete(Integer id) {
        this.deleteById(id);
    }

    @Override
    public DriverLicenseAttach selectByDriverLicenseId(Long driverLicenseId, Long driverId, String attachType) {
        return baseMapper.selectByDriverLicenseId(driverLicenseId, driverId, attachType);
    }

    /**
     * 根据传入旧的附件信息进行删除
     * @param driverLicenseAttach
     */
    @Override
    @Transactional
    public void updateOldAttachDeleteState(DriverLicenseAttach driverLicenseAttach) {
        EntityWrapper<DriverLicenseAttachHistory> ewAttach = new EntityWrapper<>();
        ewAttach.eq("driver_id", driverLicenseAttach.getDriverId());
        ewAttach.eq("license_id", driverLicenseAttach.getLicenseId());
        ewAttach.eq("attach_type", driverLicenseAttach.getAttachType());
        ewAttach.eq("attach_key", driverLicenseAttach.getAttachKey());
        List<DriverLicenseAttachHistory> driverLicenseAttachHistories = driverLicenseAttachHistoryService.selectList(ewAttach);
        if (CollectionUtils.isEmpty(driverLicenseAttachHistories)) {
            DriverLicenseAttachHistory driverLicenseAttachHistory = new DriverLicenseAttachHistory();
            BeanUtils.copyProperties(driverLicenseAttach, driverLicenseAttachHistory);
            driverLicenseAttachHistory.setGmtCreate(new Date());
            driverLicenseAttachHistory.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getUsername());
            driverLicenseAttachHistoryService.insert(driverLicenseAttachHistory);
        }
        this.deleteById(driverLicenseAttach.getId());
    }
}
